<?php
/**
 * User: hjd-yao
 * Date: 2018/11/26
 * Time: 14:24
 */

namespace Frontend\Http\Controllers;

use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Helpers\SendSMS;
use App\Models\PlatFinanceModel;
use App\Models\Shop\OrderPaymentModel;
use App\Models\User\AccountFlowModel;
use App\Models\User\RechargeRecordModel;
use DC\UserCenter\Models\UserAuthModel;
use DC\UserCenter\Models\UserWalletModel;
use DC\UserCenter\Services\UserRegister;
use Frontend\Http\Requests\RegisterRequest;
use Frontend\Http\Requests\RetrieveRequest;
use Frontend\Models\UserBaseModel;
use Illuminate\Http\Request;
use Yansongda\Pay\Pay;
use App\Models\Shop\OrderModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class LoginController extends HomeController
{

    public function login(Request $request)
    {
        if($request->isMethod('post')){
            $user_name = $request->post('username');
            $login_pwd = $request->post('password');
            $userModel = new UserBaseModel();
            if(!$userModel->login($user_name,$login_pwd)){
                return SelfResponse::error($userModel->getErrorMsg('账号或密码错误'));
            }
            return SelfResponse::success('登录成功','f_Shop_index');
        }else{
            return view('frontend::login.login',[
                'page_title'=>'登录'
            ]);
        }
    }

    public function logout()
    {
        UserBaseModel::init()->logout();
        if(\request()->ajax()){
            return \response()->json(['status'=>1,'msg'=>'退出成功','url'=>route('f_Login_showLoginForm')]);
        }
        return redirect()->route('f_Shop_index');
    }

    public function register(RegisterRequest $request)
    {
        if($request->isMethod('post')){
//            $phone_code = $request->post('phone_code');
//            $mobile = $request->post('phone');
//            $sendSMS = SendSMS::make();
//            if(!$sendSMS->checkCode($phone_code,$mobile)){
//                return SelfResponse::error($sendSMS->getErrorMsg('验证码错误'));
//            }
            $registerService = new UserRegister();
            $res = $registerService->registerByShare($request);
            if(!$res['status']){
                return SelfResponse::error($res['errorMsg']);
            }
            return SelfResponse::success('注册成功','f_Login_login');
        }else{
            return view('frontend::login.register',[
                'page_title'=>'注册',
                'code'=>$request->input('code')
            ]);
        }
    }

    public function retrievePwd(RetrieveRequest $request)
    {
        if($request->isMethod('post')){
            $phone = $request->post('phone');
            $info = UserBaseModel::where('user_phone',$phone)->first();
            if(!$info){
                return SelfResponse::error('该手机号未被注册!');
            }
            $phone_code = $request->post('phone_code');
            $sendSMS = SendSMS::make();
            if(!$sendSMS->checkCode($phone_code,$phone)){
                return SelfResponse::error($sendSMS->getErrorMsg('验证码错误'));
            }
            $user_id = $info->member_id;
            if(UserAuthModel::init()->checkLoginPwd($request->post('pwd'),$user_id)){
               return SelfResponse::success('密码重置成功','f_Login_login');
            }
            return SelfResponse::error('密码重置失败');
        }else{
            return view('frontend::login.forget_pwd',[
                'page_title'=>'找回密码'
            ]);
        }
    }

    public function sendPhoneCode(Request $request,$type='reg')
    {
        $validatedData = $request->validate([
            'phone'=>'required|mobile',
        ],[
            'required'=>':attribute不能为空',
            'mobile'=>':attribute格式不正确',
        ],[
            'phone'=>'手机号',
        ]);
        $mobile = $validatedData['phone'];
        $code = mt_rand(100000,999999);
        $sendSMS = SendSMS::make();
        $res = $sendSMS->sendCode($mobile,$code);
        if(!$res){
            return SelfResponse::error($sendSMS->getErrorMsg('发送失败'));
        }
        return SelfResponse::success('发送成功');
    }


    public function adminLogin(Request $request){


        if(!$request->has('lginfo')) {
            return redirect(route('f_Login_login'));
        }
        $client_ip = md5(get_client_ip(1));

        $lginfo = $request->input('lginfo');

        $encrypt = SelfEncrypt::decrypt($lginfo,config('encrypt.access_token'));

        $login_arr = json_decode($encrypt,true);

//        if($client_ip != $login_arr['ip']) {
//            return SelfResponse::error('登录Ip未经授权');
//        }

        $userModel = new UserBaseModel();

        if(!$userModel->adminLogin($login_arr['user_number'],$login_arr['login_pwd'])){
            return redirect(route('f_Login_login'));
        }
        return redirect(route('f_Shop_index'));
    }



    public function aliPayNtify(Request $request)
    {
        $payMentModel = new OrderPaymentModel();

        $pay_config = config('pay.alipay');

        $alipay = Pay::alipay($pay_config);

        $pay_order = $request->out_trade_no;

        $call_order = $request->trade_no;

        $check_result = $alipay->verify();
        if(!$check_result) { //回调验签失败
            return view('frontend::login.callback',[
                'page_title'=>'验签失败',
                'status'=>-1,
                'order_no'=>$pay_order
            ]);
        }

        $PaymentInfo = $payMentModel->where('out_trade_no',$pay_order)->first();
        if(!$PaymentInfo){
            return view('frontend::login.callback',[
                'page_title'=>'订单获取失败',
                'status'=>-1,
                'order_no'=>$pay_order
            ]);
        }

        $payMentModel->where('out_trade_no',$pay_order)->update([
            'trade_no'=>$call_order,
            'pay_body'=>json_encode($request->all()),
            'pay_status'=>1,
            'pay_at'=>Carbon::now()->timestamp,
        ]);
        $PaymentInfo = $payMentModel->where('out_trade_no',$pay_order)->first();

        switch ($PaymentInfo['type']){
            case '1':
                $orderModel = new OrderModel();
                $res = OrderModel::where('order_sn',$pay_order)->update([
                    'call_order'=>$call_order,
                    'pay_info'=>json_encode($request->all()),
                    'status'=>1,
                    'pay_status'=>1,
                    'pay_type'=>111,
                    'paid_at'=>Carbon::now()->timestamp
                ]);

                if($res){
                    $order_info = $orderModel->where('order_sn',$pay_order)->first();
                    $orderModel->onlinePay($order_info['uid'],$order_info);
                }
                break;
            case '2':
                $rgModel = new RechargeRecordModel();
                $res = $rgModel->where('rg_sn',$pay_order)->update([
                    'status'=>1,
                    'handled_at'=>Carbon::now()->timestamp
                ]);
                if($res){
                    $info = $rgModel->where('rg_sn',$pay_order)->first();

                    $data['money1'] = DB::raw('`money1`+'.$info['money']);
                    $data['total_rg'] = DB::raw('`total_rg`+'.$info['money']);

                    UserWalletModel::where('member_id',$info['user_id'])->update($data);

                    PlatFinanceModel::init()->countRgMoney($info['money']);

                }
        }
        return view('frontend::login.callback',[
            'page_title'=>'支付成功',
            'status'=>1,
            'order_no'=>$pay_order
        ]);

    }


    public function wechatNtify(Request $request)
    {
        $payMentModel = new OrderPaymentModel();

        $pay_config = config('pay.wechat');

        $wechat = Pay::wechat($pay_config);

        $pay_order = $request->out_trade_no;

        $call_order = $request->trade_no;

        $check_result = $wechat->verify();

        if(!$check_result) { //回调验签失败
            return view('frontend::login.callback',[
                'page_title'=>'验签失败',
                'status'=>-1,
                'order_no'=>$pay_order
            ]);
        }

        $PaymentInfo = $payMentModel->where('out_trade_no',$pay_order)->first();
        if(!$PaymentInfo){
            return view('frontend::login.callback',[
                'page_title'=>'订单获取失败',
                'status'=>-1,
                'order_no'=>$pay_order
            ]);
        }

        $payMentModel->where('out_trade_no',$pay_order)->update([
            'trade_no'=>$call_order,
            'pay_body'=>json_encode($request->all()),
            'pay_status'=>1,
            'pay_at'=>Carbon::now()->timestamp,
        ]);

        $PaymentInfo = $payMentModel->where('out_trade_no',$pay_order)->first();

        switch ($PaymentInfo['type']){
            case '1':
                $orderModel = new OrderModel();
                $res = OrderModel::where('order_sn',$pay_order)->update([
                    'call_order'=>$call_order,
                    'pay_info'=>json_encode($request->all()),
                    'status'=>1,
                    'pay_status'=>1,
                    'pay_type'=>101,
                    'paid_at'=>Carbon::now()->timestamp
                ]);

                if($res){
                     $order_info = $orderModel->where('order_sn',$pay_order)->first();
                     $orderModel->onlinePay($order_info['uid'],$order_info);
                }
                break;
            case '2':
                $rgModel = new RechargeRecordModel();
                $res = $rgModel->where('rg_sn',$pay_order)->update([
                    'status'=>1,
                    'handled_at'=>Carbon::now()->timestamp
                ]);
                if($res){
                    $info = $rgModel->where('rg_sn',$pay_order)->first();
                    $data['money1'] = DB::raw('`money1`+'.$info['money']);
                    $data['total_rg'] = DB::raw('`total_rg`+'.$info['money']);
                    UserWalletModel::where('member_id',$info['user_id'])->update($data);
                    PlatFinanceModel::init()->countRgMoney($info['money']);
                }
        }
        return view('frontend::login.callback',[
            'page_title'=>'支付成功',
            'status'=>1,
            'order_no'=>$pay_order
        ]);

    }


}